/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-05-28     Dell       the first version
 */
/*
 * 程序清单：这是一个 串口 设备使用例程
 * 例程导出了 uart_sample 命令到控制终端
 * 命令调用格式：uart_sample uart2
 * 命令解释：命令第二个参数是要使用的串口设备名称，为空则使用默认的串口设备
 * 程序功能：通过串口输出字符串"hello RT-Thread!"，然后错位输出输入的字符
*/

#include "uart.h"


/** 接收数据回调函数 **/
rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    struct rx_msg msg;

    rt_err_t result;
    msg.dev = dev;
    msg.size = size;
    result = rt_mq_send(&rx_mq, &msg, sizeof(msg));
    if(result == -RT_EFULL){
        /** 消息队列满 **/
        rt_kprintf("message queue full! \n");
    }

    return RT_EOK;
}

/** uart 接收线程 **/
void serial_thread_entry(void)
{
    struct rx_msg msg;
    rt_err_t result;
    rt_uint32_t rx_length;
    static char rx_buffer[RT_SERIAL_RB_BUFSZ + 1];

    while (1)
    {
        rt_memset(&msg, 0, sizeof(msg));
        /* 从消息队列中读取消息*/
        result = rt_mq_recv(&rx_mq, &msg, sizeof(msg), RT_WAITING_FOREVER);
        if (result == RT_EOK)
        {
            /* 从串口读取数据*/
            rx_length = rt_device_read(msg.dev, 0, rx_buffer, msg.size);
            rx_buffer[rx_length] = '\0';
            /* 通过串口设备 serial 输出读取到的消息 */
            rt_device_write(serial, 0, rx_buffer, rx_length);
            /* 打印数据 */
            rt_kprintf("%s\n",rx_buffer);
        }
    }
}

rt_err_t uart_open(const char * uart_name)
{
    rt_err_t res = RT_EOK;

    static char msg_pool[256];

    char str[] = "hello RT-Thread!\r\n";

    /** 查找串口设备 **/
    serial = rt_device_find(uart_name);

    if(!serial){

        rt_kprintf("find %s failed!\n", uart_name);
        return RT_ERROR;
    }

    /** 初始化消息队列 **/
    rt_mq_init(&rx_mq, "rx_mq",
            msg_pool,                   // 存放消息的缓冲区
            sizeof(struct rx_msg),      // 一条消息的最大长度
            sizeof(msg_pool),           // 存放消息的缓冲区大小
            RT_IPC_FLAG_FIFO);          // 如果有多个线程等待，按照先来先得到的方法分配消息

    /** 以 DMA 接收及轮询发送方式打开串口设备 **/
    rt_device_open(serial, RT_DEVICE_FLAG_DMA_RX);

    /** 设置接收回调函数 **/
    rt_device_set_rx_indicate(serial, uart_input);

    /** 发送字符串 **/
    rt_device_write(serial, 0, str, sizeof(str) - 1);

    /** 创建serial线程 **/
    rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 1024, 2, 10);

    /** 启动线程 **/
    if(thread != RT_NULL){
        rt_thread_startup(thread);
    } else {
        return RT_ERROR;
    }
    return RT_EOK;

}
